
package services

import (
	"beego_blog/models"
	"net/url"
	"strconv"
	"log"
	"time"
)

type StudentService struct {
	baseService
}

func (c *StudentService) Add(params url.Values) bool {
	student := models.Student{}
	cols := []string{}

	if params.Has("name") {
		cols = append(cols, "name")
		student.Name = params.Get("name")
	}
	if params.Has("number") {
		cols = append(cols, "name")
		student.Number = params.Get("number")
	}
	if params.Has("admit_time") {
		cols = append(cols, "name")
		student.Admit_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("admit_time"))
	}

	if _, err := c.o.Insert(&student); err != nil {
		log.Println("Add err", err)
		return false
	} else {
		return true
	}
}

func (c *StudentService) Delete(params url.Values) bool {
	student := models.Student{}
	student.Id, _ = strconv.Atoi(params.Get("id"))

	if _, err := c.o.Delete(&student); err != nil {
		log.Println("Delete err", err)
		return false
	} else {
		return true
	}
}

func (c *StudentService) Query(params url.Values) []*models.Student {
	students := []*models.Student{}
	student := models.Student{}
	cols := []string{}

	if params.Has("name") {
		cols = append(cols, "name")
		student.Name = params.Get("name")
	}
	if params.Has("number") {
		cols = append(cols, "name")
		student.Number = params.Get("number")
	}
	if params.Has("admit_time") {
		cols = append(cols, "name")
		student.Admit_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("admit_time"))
	}

	Query_by_model(c.o, "id", cols, student, &students)
	return students
}

func (c *StudentService) QueryByPk(params url.Values) models.Student {
	student := models.Student{}
	student.Id, _ = strconv.Atoi(params.Get("id"))

	c.o.Read(&student)
	return student
}

func (c *StudentService) Update(params url.Values) bool {
	student := models.Student{}
	cols := []string{}
	student.Id, _ = strconv.Atoi(params.Get("id"))

	if params.Has("name") {
		cols = append(cols, "name")
		student.Name = params.Get("name")
	}
	if params.Has("number") {
		cols = append(cols, "name")
		student.Number = params.Get("number")
	}
	if params.Has("admit_time") {
		cols = append(cols, "name")
		student.Admit_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("admit_time"))
	}

	if _, err := c.o.Update(&student, cols...); err != nil {
		log.Println("Update err", err)
		return false
	} else {
		return true
	}
}
	
